package org.example;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.example.Model.RequestData;
import org.example.Model.ResponseData;
import org.example.Model.User;
import org.example.serialize.JdkSerializer;
import org.example.serialize.Serializer;
import org.example.service.UserService;

public class UserServiceProxy implements UserService {
    @Override
    public User getUser(User user) {
        // 指定序列化器
        Serializer serializer = new JdkSerializer();
        // 准备发送数据
        RequestData requestData = new RequestData().builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .parameterTypes(new Class[]{User.class})
                .args(new Object[]{user})
                .build();
        // 序列化请求数据
        try {
            byte[] bytes = serializer.serialize(requestData);
            HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
                    .body(bytes)
                    .execute();
            ResponseData responseData = serializer.deserialize(httpResponse.bodyBytes(), ResponseData.class);
            return (User) responseData.getData();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
